const chatInput = document.getElementById('chat-input');
const sendButton = document.getElementById('button-send');
const containerMessages = document.getElementById('container-messages');
const loadingSpinner = createLoadingSpinner()

const chatInputLearn1 = document.getElementById('chat-input-learn1');
const sendButtonLearn1 = document.getElementById('button-send-learn1');
const containerMessagesLearn1 = document.getElementById('container-messages-learn1');

const chatInputLearn2 = document.getElementById('chat-input-learn2');
const sendButtonLearn2 = document.getElementById('button-send-learn2');
const containerMessagesLearn2 = document.getElementById('container-messages-learn2');

const chatInputEntertainment1 = document.getElementById('chat-input-entertainment1');
const sendButtonEntertainment1 = document.getElementById('button-send-entertainment1');
const containerMessagesEntertainment1 = document.getElementById('container-messages-entertainment1');

const chatInputEntertainment2 = document.getElementById('chat-input-entertainment2');
const sendButtonEntertainment2 = document.getElementById('button-send-entertainment2');
const containerMessagesEntertainment2 = document.getElementById('container-messages-entertainment2');

//creates loading animation
function createLoadingSpinner() {
    const loadingSpinner = document.createElement('div');
    loadingSpinner.className = 'loading-spinner';
    const spinnerBorder = document.createElement('div');
    spinnerBorder.className = 'spinner-grow';
    spinnerBorder.role = 'status';

    const visuallyHiddenSpan = document.createElement('span');
    visuallyHiddenSpan.className = 'visually-hidden';
    visuallyHiddenSpan.textContent = 'Loading...';

    spinnerBorder.appendChild(visuallyHiddenSpan);
    loadingSpinner.appendChild(spinnerBorder);
    return loadingSpinner
}

function createUserMessage(message) {
    const newMessageContainer = document.createElement('div');
    newMessageContainer.className = 'right-message-container';
    const newMessageDiv = document.createElement('div');
    newMessageDiv.className = 'right-message';
    newMessageDiv.innerHTML = `<p class="m-0">${message}</p>`;
    newMessageContainer.appendChild(newMessageDiv);
    return newMessageContainer
}

sendButton.addEventListener('click', async () => {
    const message = chatInput.value.trim();
    if (message !== '') {
        const currentChatWindowId = getCurrentChatWindowId();
        const currentContainerMessages = containerMessages;

        // Creates instances of message and spinner
        const newMessageDiv = createUserMessage(message);
        currentContainerMessages.appendChild(newMessageDiv);
        currentContainerMessages.appendChild(loadingSpinner);

        //cleans up input and disables it, so another message cannot be queried
        chatInput.value = '';
        chatInput.disabled = true

        // Sends message to the server
        await fetchData(message, currentChatWindowId, currentContainerMessages,chatInput);
        // Scroll to the newly added message
        newMessageDiv.scrollIntoView({behavior: 'smooth'});
    }
});

sendButtonLearn1.addEventListener('click', async () => {
    const message = chatInputLearn1.value.trim();
    const file = document.getElementById('image-upload-learn1').files[0]; // 获取图片文件
    const from_lang = document.getElementById('language-from').value; // 获取源语言
    const to_lang = document.getElementById('language-to').value; // 获取目标语言

    //if (message !== '') {
        const currentChatWindowId = "learn1";
        const currentContainerMessages = containerMessagesLearn1;

        // Creates instances of message and spinner
        const newMessageDiv = createUserMessage(message);
        currentContainerMessages.appendChild(newMessageDiv);
        currentContainerMessages.appendChild(loadingSpinner);

        // Cleans up input and disables it, so another message cannot be queried
        chatInputLearn1.value = '';
        chatInputLearn1.disabled = true;

        // Creates FormData object and appends fields to it
        const formData = new FormData();
        formData.append('question', message);
        formData.append('file', file);
        formData.append('from_lang', from_lang);
        formData.append('to_lang', to_lang);
        formData.append('stream', true);
        formData.append('chatId', currentChatWindowId);

        console.log(formData);

        // Sends message to the server using FormData
        await fetchDataLearn1(formData, currentContainerMessages);

        // Scroll to the newly added message
        newMessageDiv.scrollIntoView({behavior: 'smooth'});
   // }
});


sendButtonLearn2.addEventListener('click', async () => {
    const message = chatInputLearn2.value.trim();
    if (message !== '') {
        const currentChatWindowId = getCurrentChatWindowId();
        const currentContainerMessages = containerMessagesLearn2;

        // Creates instances of message and spinner
        const newMessageDiv = createUserMessage(message);
        currentContainerMessages.appendChild(newMessageDiv);
        currentContainerMessages.appendChild(loadingSpinner);

        //cleans up input and disables it, so another message cannot be queried
        chatInputLearn2.value = '';
        chatInputLearn2.disabled = true

        //sends message to the server
        await fetchData(message, currentChatWindowId, currentContainerMessages, chatInputLearn2)
        // Scroll to the newly added message
        newMessageDiv.scrollIntoView({behavior: 'smooth'});
    }
});

sendButtonEntertainment1.addEventListener('click', async () => {
    const message = chatInputEntertainment1.value.trim();
    if (message !== '') {
        const currentChatWindowId = getCurrentChatWindowId();
        const currentContainerMessages = containerMessagesEntertainment1;

        // Creates instances of message and spinner
        const newMessageDiv = createUserMessage(message);
        currentContainerMessages.appendChild(newMessageDiv);
        currentContainerMessages.appendChild(loadingSpinner);

        //cleans up input and disables it, so another message cannot be queried
        chatInputEntertainment1.value = '';
        chatInputEntertainment1.disabled = true

        //sends message to the server
        await fetchData(message, currentChatWindowId, currentContainerMessages, chatInputEntertainment1)

        // Scroll to the newly added message
        newMessageDiv.scrollIntoView({behavior: 'smooth'});
    }
});

sendButtonEntertainment2.addEventListener('click', async () => {
    const message = chatInputEntertainment1.value.trim();
    if (message !== '') {
        const currentChatWindowId = getCurrentChatWindowId();
        const currentContainerMessages = containerMessagesEntertainment2;

        // Creates instances of message and spinner
        const newMessageDiv = createUserMessage(message);
        currentContainerMessages.appendChild(newMessageDiv);
        currentContainerMessages.appendChild(loadingSpinner);

        //cleans up input and disables it, so another message cannot be queried
        chatInputEntertainment2.value = '';
        chatInputEntertainment2.disabled = true

        //sends message to the server
        await fetchData(message, currentChatWindowId, currentContainerMessages, chatInputEntertainment2)
        // Scroll to the newly added message
        newMessageDiv.scrollIntoView({behavior: 'smooth'});
    }
});

// Sends data to the server
async function fetchData(message, chatId, containerMessages, chatInput) {
    const response = await fetch('/ask', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: message,
            stream: true,
            chatId: chatId
        })
    }).catch(error => console.error('Error:', error));

    await decodeAndSet(response, containerMessages, chatInput); // Pass the containerMessages for specific window
}

// Sends data to the server
async function fetchDataLearn1(formData, containerMessages) {
    const response = await fetch('/translate', {
        method: 'POST',
        body: formData
    }).catch(error => console.error('Error:', error));

    await decodeAndSet(response, containerMessages, chatInputLearn1);
}


// Decodes the response and sets response as message
async function decodeAndSet(response, containerMessages, chatInput) {
    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');

    loadingSpinner.remove();
    cleanLast(containerMessages); // Clear the last class for the current chat window

    const leftMessageDiv = document.createElement('div');
    leftMessageDiv.className = 'left-message last';

    containerMessages.appendChild(leftMessageDiv);

    let textArray = '';

    while (true) {
        const chunk = await reader.read();
        const { done, value } = chunk;
        if (done) {
            leftMessageDiv.innerHTML = formatText(textArray);
            chatInput.disabled = false;
            break;
        }
        const text = decoder.decode(value);

        leftMessageDiv.innerHTML += `<span class="m-0">${text}</span>`;
        textArray += text;
    }
}


// Cleans 'last' class from the last message in the specific container
function cleanLast(containerMessages) {
    const previousMessages = containerMessages.querySelectorAll('.left-message.last');
    previousMessages.forEach((message) => message.classList.remove('last'));
}




//formats received text
function formatText(text) {

    const formattedText = text
        .replace('chat:', '')
        .replace(/\\n/g, '<br/>') // replace multiple newline characters with paragraph breaks
        .replace(/^\d+\./gm, '<p><b>$&</b>') // format numbered list items
        .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>') // format bold text
        .replace(/\[(.+?)\]/g, '<a href="#">$1</a>') // format links
        .replace(/<p><\/p>/g, ''); // remove empty paragraphs
    return formattedText;
}

//allows to enter message with Enter button
document.addEventListener('keypress', function (event) {
    if (event.key === 'Enter') {
        document.getElementById('button-send').click();
    }
});

// Function to load and display conversation history
function loadConversationHistory(chatId) {
    fetch('/get_conversation_history')
        .then(response => response.json())
        .then(data => {
            const messagesContainer = document.getElementById('container-messages');
            const conversationTurn = data[chatId];
            
            if (!conversationTurn) return;

            messagesContainer.innerHTML = '';

            conversationTurn.forEach(turn => {
                if(turn.role === 'system') return;
                const messageClass = turn.role === 'user' ? 'right-message' : 'left-message';

                // 创建消息元素
                const messageElement = document.createElement('div');
                messageElement.className = messageClass;

                // 创建消息段落
                const paragraph = document.createElement('p');
                paragraph.className = 'm-0';

                // 根据角色设置内容
                paragraph.innerHTML = turn.role === 'user' ? 
                    turn.content : 
                    formatText(turn.content); // 注意这里改用content而不是text

                // 添加到消息容器
                messageElement.appendChild(paragraph);
                messagesContainer.appendChild(messageElement);
            });
        })
        .catch(error => {
            console.error('Error fetching conversation history:', error);
        });
}

function loadHistory() {
    fetch('/get_chat_info')
        .then(response => response.json())
        .then(data => {
//            console.log(data);
            if (data && Object.keys(data).length > 0) {
                for (const key in data) {
                    if (data.hasOwnProperty(key)) {
                        loadChat(key, data[key]);
                    }
                }
            }
            else {
                newChat();
            }
            clearAdditionalMessages();
            clickCurrentChat();
        })
        .catch(error => {
            console.error('Error fetching conversation history:', error);
        });
}

window.addEventListener('load', loadHistory);

function getCurrentChatWindowId() {
    const chatItems = document.querySelectorAll('.chat_item li');

    console.log(`Found ${chatItems.length} chat items`);

    for (const chatItem of chatItems) {
        const aElement = chatItem.querySelector('a');

        if (aElement && aElement.classList.contains('active')) {
            const chatId = chatItem.getAttribute('id');
            console.log(`Active chat item found with ID: ${chatId}`);
            return chatId;
        }
    }

    // If no chat item is active, log an error and return null
    console.error('No active chat window found.');
    return null; // Or handle according to your application's requirements
}


function clearAdditionalMessages() {
    // 获取 #container-messages 元素
    const containerMessages = document.getElementById('container-messages');

    const messages = Array.from(containerMessages.children);

    for (let i = messages.length - 1; i > 0; i--) {
        containerMessages.removeChild(messages[i]);
    }
}